<?php
/**
 * Date: 2024.8
 * Author: kahn
 */
namespace service\uc\oauth;

class WeixinAppClient  extends BaseAuthClient
{
    CONST USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo';
    CONST AUTHORIZE_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
    CONST OAUTH_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/access_token';

    public function getAccessToken($code)
    {
        $params = array(
            'appid' => $this->config['appId'],
            'secret' => $this->config['secret'],
            'code' => $code,
            'grant_type' => 'authorization_code'
        );
        $result = $this->getRequest(self::OAUTH_TOKEN_URL, $params);
        $rawToken = json_decode($result, true);
        if(isset($rawToken['errcode'])){
            return ['error'=>$rawToken['errcode'],'errmsg'=>$rawToken['errmsg']];
        }
        return  array(
            'expiredTime' => $rawToken['expires_in'],
            'access_token' => $rawToken['access_token'],
            'token' => $rawToken['access_token'],
            'openid' => $rawToken['openid'],
            'unionid' => $rawToken['unionid'] ?? ''
        );
    }

    public function getUserInfo($token)
    {
        $params = array(
            'openid' => $token['openid'] ,
            'access_token' => $token['access_token'],
            'lang' => 'zh_CN');
        $result = $this->getRequest(self::USERINFO_URL, $params);
        $info = json_decode($result, true);
        return $this->convertUserInfo($info);
    }

    private function convertUserInfo ($infos) {
        $userInfo = array();
        $userInfo['id'] = isset($infos['unionid'])?$infos['unionid']:$infos['openid'];
        $userInfo['name'] = $infos['nickname'];
        $userInfo['smallAvatar'] = $infos['headimgurl'];
        return $userInfo;
    }

}